<?php
date_default_timezone_set('America/Chicago');

session_start();
//Include DB Credentials and Connection
//Credentials and Database Name	
$dbServer = "localhost";
$dbUser = "root";
$dbPass = "3lch@rr099";
$dbName = "shellicio_us";

// Generate Random Alpha Numeric String
function generateRandomString($length = 8) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

// Generate Random Numeric String
function generateNumber($length = 8) {
    $characters = '0123456789';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

// Human Readable Seconds
function secs_to_h($secs) {
        $units = array(
                "week"   => 7*24*3600,
                "day"    =>   24*3600,
                "hour"   =>      3600,
                "minute" =>        60,
                "second" =>         1,
        );

	// specifically handle zero
        if ( $secs == 0 ) return "0 seconds";

        $s = "";

        foreach ( $units as $name => $divisor ) {
                if ( $quot = intval($secs / $divisor) ) {
                        $s .= "$quot $name";
                        $s .= (abs($quot) > 1 ? "s" : "") . ", ";
                        $secs -= $quot * $divisor;
                }
        }

        return substr($s, 0, -2);
}

// Write Credentials Files
function writeCredentials() {
	$file = "/web/shellicio.us/creds/" . $_SESSION['session_user'] . ".txt";
	if (file_exists($file)) {
	} else {
		// Open the file to get existing content
		$current = file_get_contents($file);
		// Append a new person to the file
		$current .= '<html>';
		$current .= '<div style=font-size:1.3em;>Thank you for using Shellicio.us! Here is your receipt.</div><br />';		
		$current .= '<div style=font-size:1em;><table><tr><td><img src="https://shellicio.us/images/logo_email.png"></td><td>';
		$current .= "Shellicio.us Credentials<br />";
		$current .= "========================<br /><br />";	
		$current .= "Username: <span style=font-size:1.4em;font-weight:bold;background-color:#ffffcc;>" . $_SESSION['session_user'] . "</span><br />";
		$current .= "Password: <span style=font-size:1.4em;font-weight:bold;background-color:#ffffcc;>" . $_SESSION['session_pass'] . "</span><br />";
		$current .= "Web Location: <span style=font-size:1.4em;font-weight:bold;background-color:#ffffcc;>https://shellicio.us/~" . $_SESSION['session_user'] . "</span><br />";
		$current .= '</td></tr></table><br />';
		$current .= '<div style=font-size:1.3em;>If you need assistance, please email <a href="mailto:contact@joestrusz.com?subject=Support">contact@shellicio.us</a>. This set of credentials will expire on <b>'.date('F jS, Y',$_SESSION['session_time_stop']).'</b> at <b>'.date('h:i:s A',$_SESSION['session_time_stop']).'</b>.</div><br />';
		$current .= '<div style=font-size:1.3em;>&copy; Shellicio.us - All rights reserved.</div></div>';
		$current .= '</html>';		
		// Write the contents back to the file
		file_put_contents($file, $current);
	}	
}




//Returns Pretty Duration from Seconds
function getNiceDuration($durationInSeconds) {

  $duration = '';
  $years = floor($durationInSeconds / 31536000);
  $days = floor($durationInSeconds / 86400);
  $durationInSeconds -= $days * 86400;
  $hours = floor($durationInSeconds / 3600);
  $durationInSeconds -= $hours * 3600;
  $minutes = floor($durationInSeconds / 60);
  $seconds = $durationInSeconds - $minutes * 60;

  if($years > 0) {
  	$duration .= $years . ' years, ';
  }
  if($days > 0) {
  	if($days >= 365) {
  		$yearDays = $years * 365;
  		$newDays = $days - $yearDays;
  		if($newDays == 1) {
    		$duration .= $newDays . ' day, ';
  		} else {
    		$duration .= $newDays . ' days, ';
  		}
    } else {
  		if($newDays == 1) {
    		$duration .= $days . ' day,';
    	} else {
    		$duration .= $days . ' days,';
    	}
    }
  }
  if($hours > 0) {
	  if($hours == 1) {
      	$duration .= ' ' . $hours . ' hour,';
	  } else {
      	$duration .= ' ' . $hours . ' hours,';
	  }
  }
  if($minutes > 0) {
  	if($minutes == 1){
    	$duration .= ' ' . $minutes . ' minute, and ';
  	} else {
    	$duration .= ' ' . $minutes . ' minutes and ';
  	}
  }
  if($seconds > 0) {
  	if($duration == 1){
    	$duration .= ' ' . $seconds . ' second';
  	} else {
    	$duration .= ' ' . $seconds . ' seconds';
  	}
  }
  return $duration;

//Ends Pretty Duration from Seconds
}

//GeoIP
function getLocationInfoByIp($ip_addr)
{
    $return_data  = array('country'=>'', 'city'=>'');
    $ip_data = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=".$ip_addr));
    if($ip_data && $ip_data->geoplugin_countryName != null)
    {
        $return_data['country'] = $ip_data->geoplugin_countryCode;
        $return_data['city'] = $ip_data->geoplugin_city;
        $return_data['state'] = $ip_data->geoplugin_region;
        $return_data['lat'] = $ip_data->geoplugin_latitude;
        $return_data['long'] = $ip_data->geoplugin_longitude;        
    }
    $url = "http://api.tiles.mapbox.com/v4/examples.map-zr0njcqy/pin-s-bus+f44(".$return_data['long'].",".$return_data['lat'].",8)/".$return_data['long'].",".$return_data['lat'].",8/500x297.png?access_token=pk.eyJ1Ijoic2hlbGxpY2lvdXMiLCJhIjoiQXVHWENRYyJ9.ew4a6O10OTSwzWgEBMw0vg";
    $javaScript = "$('#locationDialog').html('<img style=width:100%;height:100%;border-radius:10px; src=$url>').modal();$('#simplemodal-container').corner('10px');$('.simplemodal-data,.simplemodal-container').corner('10px').css('padding','0px');";
    return '<a href="#" onClick="'.$javaScript.'">'.$return_data['city'].' '.$return_data['state'].'</a>';

}   

$function = $_GET['function'];
switch ($function) {
	
	//Start newCred Function
	case "newCred":
	
		// Server should keep session data for AT LEAST 12 hours
		ini_set('session.gc_maxlifetime', 43200);
		
		// Each client should remember their session id for EXACTLY 12 hours
		session_set_cookie_params(43200);
			
		// Session Length
		$timeout = 43200;
		
		// Start Session
		session_start();
		
		// Check if Session Already Exists
		if(!isset($_SESSION['session_identifier'])) { 
			// If We Haven't Created our Special Session, Do So Now
			$_SESSION['session_identifier'] = "Shellicio.us Session";
			$_SESSION['session_user'] = generateRandomString(); 
			$_SESSION['session_pass'] = generateNumber('4');
			$_SESSION['session_ip'] = $_SERVER['REMOTE_ADDR'];
			$_SESSION['session_email'] = $_GET['email'];
			$_SESSION['session_browser'] = $_SERVER['HTTP_USER_AGENT'];
			$_SESSION['session_time_start'] = time();	
			$_SESSION['session_time_stop'] = time() + $timeout;	
		}
		
		// Check if Session is Expired, If so, Destroy
		if($_SESSION['session_time_stop'] < time()) {
			session_destroy();
		}
		
		$timeleft = $_SESSION['session_time_stop'] - time();
		
		writeCredentials();	
	
		//Grab the POST Values and make them Pretty
		$usernameCred = $_SESSION['session_user'];
		$usernamePass = $_SESSION['session_pass'];
		$credEmail = $_GET['email'];		
	
		//Launches our Create user Script - Accepts add/update username password	
		$command = "sudo /scripts/adduser.sh add $usernameCred $usernamePass";
		system("".$command."");
	
		//Emails the User and System Administartor the new Credentials	
		system('sudo cat /web/shellicio.us/creds/'.$usernameCred.'.txt | mail -s "$(echo "[Shellicio.us] Credentials Receipt\nContent-Type: text/html")" -a "From: Shellicio.us Support <contact@shellicio.us>" '.$credEmail.' contact@shellicio.us');
		echo "Done! Credentials emailed to " . $credEmail . " for user " . $usernameCred . ".";
	
		//Create connection
		mysql_connect($dbServer, $dbUser, $dbPass);
		mysql_select_db($dbName) or die( "Unable to select database");
		
		$insertIP = $_SERVER['REMOTE_ADDR'];
		$insertStartTime = $_SESSION['session_time_start'];
		$insertStopTime = $_SESSION['session_time_stop'];
		
		//The Query
		//Check if Premium User
		//$premiumUserList = array(
			//Start Actual Premium User List
			//'joe.strusz@gmail.com',
			//'mindamp@gmail.com',
			//'contact@joestrusz.com'
			//End Actual Premium User List
			//);
		//if (in_array($credEmail, $premiumUserList)) {
			//$sql = "INSERT INTO sessions (username,password,email,db_database,db_username,db_password,ip_address,start_time,stop_time,status) VALUES ('$usernameCred','$usernamePass','$credEmail','db_$usernameCred','$usernameCred','$usernamePass','$insertIP','$insertStartTime','$insertStopTime','enabled','true');";
		//} else {
			$sql = "INSERT INTO sessions (username,password,email,db_database,db_username,db_password,ip_address,start_time,stop_time,status,premium) VALUES ('$usernameCred','$usernamePass','$credEmail','db_$usernameCred','$usernameCred','$usernamePass','$insertIP','$insertStartTime','$insertStopTime','enabled','false');";
		//}
		//Execute the Query
		mysql_query($sql);
		
		//Close Connection
		mysql_close();
	
		//End newCred Function	
		
	break;
	
	//Start listCred Function
	case "listCred":

		//Start Connection
		$con=mysqli_connect($dbServer,$dbUser,$dbPass,$dbName);
		// Check connection
		if (mysqli_connect_errno())
		{
		echo "Failed to connect to MySQL: " . mysqli_connect_error();
		}
		
		//MySQL Query
		$result = mysqli_query($con,"SELECT * FROM sessions WHERE status = 'enabled'");
		
		//Display Results		
		echo '<table id="credentialListTable" class="display" style="font-size:.7em !important;">';
	
		//Define Rows for Header on Table
		$rowsHeaderHTML = '<tr>';
	    $rowsHeaderHTML .= '<th style="border-top-left-radius:10px;border-top-right-radius:0px;text-align:left;padding-left:10px;">Session ID</th>';	
	    $rowsHeaderHTML .= '<th>Session User</th>';
	    $rowsHeaderHTML .= '<th>Session Start</th>';
	    $rowsHeaderHTML .= '<th>Session Origin</th>';
	    $rowsHeaderHTML .= '<th>IP Address</th>';
	    $rowsHeaderHTML .= '<th style="border-top-left-radius:0px;border-top-right-radius:10px;text-align:right;padding-right:20px;">Time Remaining</th>';
		$rowHeadersHTML .= '</tr>';
		//End Row Definition
	
		echo '<thead style="background-color:white;">';
		echo $rowsHeaderHTML;
		echo '</thead>';
		echo '<tbody>';
		//Individual Results HTML
		while($row = mysqli_fetch_array($result)) {
			$stopTime = $row["stop_time"];
			$startTime = $row["start_time"];
			$currentTime = time();
			$timeRemaining = $stopTime - $currentTime;
			$userNameStock = $row['username'];
			$row['username'][2]='*';
			$row['username'][3]='*';
			$row['username'][4]='*';
			$row['username'][5]='*';	
			$row['username'][6]='*';		
			$row['username'][7]='*';
			$ipAddress = $row['ip_address'];		
			//$row['ip_address'][0]='*';		
			//$row['ip_address'][1]='*';
			$row['ip_address'][2]='*';
			$row['ip_address'][3]='*';
			$row['ip_address'][4]='*';	
			$row['ip_address'][5]='*';		
			$row['ip_address'][6]='*';
			$row['ip_address'][7]='*';							
			$row['ip_address'][8]='*';							
			$row['ip_address'][9]='*';							
			$row['ip_address'][10]='*';							
			$row['ip_address'][11]='*';
			$row['ip_address'][12]='*';
			$row['ip_address'][13]='*';
			$row['ip_address'][14]='*';		
			
			if ($row['premium'] == 'true') {
				echo "<tr style=\"background-color:#e6ffe6;\">";
				echo "<td style=text-align:left;padding-left:10px;background-color:#e6ffe6;>" . $row['id'] . "</td>";		
				echo "<td style=background-color:#e6ffe6;>" . $row['username'] . "</td>";
				echo "<td style=background-color:#e6ffe6;>" . date('m/d/Y h:i:s A T',$row["start_time"]) . "</td>";
		
				echo "<td style=background-color:#e6ffe6;>Premium User</td>";
				echo "<td style=background-color:#e6ffe6;>Premium User</td>";		
				echo "<td style=text-align:right;padding-right:10px;background-color:#e6ffe6;>" . getNiceDuration($timeRemaining) . "</td>";
				echo "</tr>";			
			} else {													
				echo "<tr>";
				echo "<td style=text-align:left;padding-left:10px;>" . $row['id'] . "</td>";		
				echo "<td>" . $userNameStock . "</td>";
				echo "<td>" . date('m/d/Y h:i:s A T',$row["start_time"]) . "</td>";	
				echo "<td>" . getLocationInfoByIp($ipAddress) . "</td>";
				echo "<td>" . $row['ip_address'] . "</td>";		
				echo "<td style=text-align:right;padding-right:10px;>" . getNiceDuration($timeRemaining) . "</td>";
				echo "</tr>";
			}	
		}
		echo '</tbody>';
		echo '<tfoot style="background-color:white;">';
		//Define Rows for Footer on Table
		$rowsFooterHTML = '<tr style="background-color:white;">';
	    $rowsFooterHTML .= '<th style="text-align:left;padding-left:10px;">Session ID</th>';	
	    $rowsFooterHTML .= '<th>Session User</th>';
	    $rowsFooterHTML .= '<th>Session Start</th>';
	    $rowsFooterHTML .= '<th>Session Origin</th>';
	    $rowsFooterHTML .= '<th>IP Address</th>';
	    $rowsFooterHTML .= '<th style="text-align:right;padding-right:20px;">Time Remaining</th>';
		$rowsFooterHTML .= '</tr>';
		//End Row Definition
		echo $rowsFooterHTML;
		echo '</tfoot>';	
		echo "</table>";
		echo "<script>$('#credentialListTable').DataTable({'autoWidth': true,'iDisplayLength': 7,'order': [[ 0, 'desc' ]],'bFilter': false,'bLengthChange': false});$('.dataTables_info').css('padding-left','10px');$('#credentialListTable_wrapper').css('border-radius','10px');</script>";
	
		mysql_close();
		mysql_close();
		mysql_close();
		//End listCred Function

	break;
	
	case "logout":

		session_unset();
		session_destroy();
		$_SESSION['admin'] = false;
		
		header('Location: https://shellicio.us');
	
	break;
	
	case "login":

		//Start login Function
		$email = $_GET['email'];
		$password = md5($_GET['pass']);
	
		//Start Connection
		$mysqli = new mysqli($dbServer,$dbUser,$dbPass,$dbName);
		
		/* check connection */
		if (mysqli_connect_errno()) {
		    printf("Connect failed: %s\n", mysqli_connect_error());
		    exit();
		}
		
		if ($result = $mysqli->query("SELECT * FROM users WHERE email = '$email' AND password = '$password'")) {
		
		    /* determine number of rows result set */
		    $row_cnt = $result->num_rows;
		
		    if($row_cnt >= 1) {
		    	//update last_login
		    	$now = time();
		    	$mysqli->query("UPDATE users SET last_login = '$now' WHERE email = '$email'");
				// If We Haven't Created our Special Session, Do So Now
				$_SESSION['session_identifier'] = "Shellicio.us Session"; 
				$_SESSION['session_pass'] = "";
				$_SESSION['session_ip'] = $_SERVER['REMOTE_ADDR'];
				$_SESSION['session_email'] = $email;
				$_SESSION['session_browser'] = $_SERVER['HTTP_USER_AGENT'];
				$_SESSION['session_time_start'] = "";	
				$_SESSION['session_time_stop'] = "";
				$_SESSION['session_premium'] = "true";
				while($row = mysqli_fetch_array($result)) {
					$_SESSION['session_user'] = $row['username'];
					if ($row['admin'] == 'true') {
						$_SESSION['admin'] = "true";
					}
				}
				print_r($result);			
		    } else {
	        	header('HTTP/1.1 500 Internal Server Booboo');
				header('Content-Type: application/json; charset=UTF-8');
				die(json_encode(array('message' => 'ERROR', 'code' => 1337)));
	  	    }
		
		    /* close result set */
		    $result->close();
		} else {
	        header('HTTP/1.1 500 Internal Server Booboo');
			header('Content-Type: application/json; charset=UTF-8');
			die(json_encode(array('message' => 'ERROR', 'code' => 1337)));		
		}
		
		/* close connection */
		$mysqli->close();
	
		//End login Function
			
	break;
	
	case "updateUserInfo":

		//Start updateUserInfo Function
		$field = $_GET['field'];		
		$username = $_GET['username'];
		if($field == 'password') {
			$value = md5($_GET['value']);
		} else {
			$value = $_GET['value'];	
		}
	
		if(empty($value)) {
		
			header('HTTP/1.1 500 Internal Server Booboo');
			header('Content-Type: application/json; charset=UTF-8');
			die(json_encode(array('message' => 'ERROR', 'code' => 1337)));
		
		} else {
		
			//Start Connection
			$mysqli = new mysqli($dbServer,$dbUser,$dbPass,$dbName);
			
			/* check connection */
			if (mysqli_connect_errno()) {
			    printf("Connect failed: %s\n", mysqli_connect_error());
			    exit();
			}
			
			$mysqli->query("UPDATE users SET $field = '$value' WHERE username = '$username'");
			
			/* close connection */
			$mysqli->close();
		
			return true;
			//End updateUserInfo Function
		}
		
	break;
	
	case "createMemberCredential":
		
		//Some Needed Values from the Session and POST etc...
		$owner = $_SESSION['session_user'];
		$expiration = $now = strtotime ($_GET['expiration']);
		$usernameCred = generateRandomString();
		$usernamePass = generateNumber('4');
		$credEmail = $_SESSION['session_email'];
				
		//echo "Owner: ".$owner." | Expiration Date: ".$expiration;
	
		//Launches our Create user Script - Accepts add/update username password	
		$command = "sudo /scripts/adduser.sh add $usernameCred $usernamePass";
		system("".$command."");
	
		//Create connection
		mysql_connect($dbServer, $dbUser, $dbPass);
		mysql_select_db($dbName) or die( "Unable to select database");
		
		$insertIP = $_SERVER['REMOTE_ADDR'];
		$insertStartTime = time();
		$insertStopTime = $expiration;
		
		$sql = "INSERT INTO sessions (username,password,email,db_database,db_username,db_password,ip_address,start_time,stop_time,status,premium,owner) VALUES ('$usernameCred','$usernamePass','$credEmail','db_$usernameCred','$usernameCred','$usernamePass','$insertIP','$insertStartTime','$insertStopTime','enabled','true','$owner');";

		echo $sql;

		//Execute the Query
		mysql_query($sql);
		
		//Close Connection
		mysql_close();
	
	break;

	//Start listCred Function
	case "userListCred":

		//Start Connection
		$con=mysqli_connect($dbServer,$dbUser,$dbPass,$dbName);
		// Check connection
		if (mysqli_connect_errno())
		{
		echo "Failed to connect to MySQL: " . mysqli_connect_error();
		}
		
		$owner = $_SESSION['session_user'];
		//MySQL Query
		$result = mysqli_query($con,"SELECT * FROM sessions WHERE status = 'enabled' AND owner = '$owner'");
			
		//Display Results		
		echo '<table id="credentialUserListTable" class="display" style="font-size:.7em !important;">';
	
		//Define Rows for Header on Table
		$rowsHeaderHTML = '<tr>';
	    $rowsHeaderHTML .= '<th style="border-top-left-radius:10px;border-top-right-radius:0px;text-align:left;padding-left:10px;">Session ID</th>';	
	    $rowsHeaderHTML .= '<th>Session User</th>';
	    $rowsHeaderHTML .= '<th>Session Password</th>';
	    $rowsHeaderHTML .= '<th>Session Start</th>';
	    $rowsHeaderHTML .= '<th>Session Origin</th>';
	    $rowsHeaderHTML .= '<th>IP Address</th>';
	    $rowsHeaderHTML .= '<th style="border-top-left-radius:0px;border-top-right-radius:10px;text-align:right;padding-right:20px;">Time Remaining</th>';
		$rowHeadersHTML .= '</tr>';
		//End Row Definition
	
		echo '<thead style="background-color:white;">';
		echo $rowsHeaderHTML;
		echo '</thead>';
		echo '<tbody>';
		//Individual Results HTML
		$row_cnt = $result->num_rows;											
		
		if($row_cnt != "0") {
			while($row = mysqli_fetch_array($result)) {
				$stopTime = $row["stop_time"];
				$startTime = $row["start_time"];
				$currentTime = time();
				$timeRemaining = $stopTime - $currentTime;
				$userNameStock = $row['username'];
				$ipAddress = $row['ip_address'];		
				
				echo "<tr>";
				echo "<td style=text-align:left;padding-left:10px;>" . $row['id'] . "</td>";		
				echo "<td>" . $userNameStock . "</td>";
				echo "<td>" . $row['password'] . "</td>";
				echo "<td>" . date('m/d/Y h:i:s A T',$row["start_time"]) . "</td>";	
				echo "<td>" . getLocationInfoByIp($ipAddress) . "</td>";
				echo "<td>" . $row['ip_address'] . "</td>";		
				echo "<td style=text-align:right;padding-right:10px;>" . getNiceDuration($timeRemaining) . "</td>";
				echo "</tr>";
			}
		} else {
			echo "<tr>";
			echo "<td style=text-align:center;>NA</td>";
			echo "<td style=text-align:center;>NA</td>";
			echo "<td style=text-align:center;>NA</td>";
			echo "<td style=text-align:center;>NA</td>";
			echo "<td style=text-align:center;>NA</td>";
			echo "<td style=text-align:center;>NA</td>";
			echo "<td style=text-align:center;>NA</td>";
			echo "</tr>";
		}
		echo '</tbody>';
		echo '<tfoot style="background-color:white;">';
		//Define Rows for Footer on Table
		$rowsFooterHTML = '<tr style="background-color:white;">';
	    $rowsFooterHTML .= '<th style="text-align:left;padding-left:10px;">Session ID</th>';	
	    $rowsFooterHTML .= '<th>Session User</th>';
	    $rowsFooterHTML .= '<th>Session Password</th>';
	    $rowsFooterHTML .= '<th>Session Start</th>';
	    $rowsFooterHTML .= '<th>Session Origin</th>';
	    $rowsFooterHTML .= '<th>IP Address</th>';
	    $rowsFooterHTML .= '<th style="text-align:right;padding-right:20px;">Time Remaining</th>';
		$rowsFooterHTML .= '</tr>';
		//End Row Definition
		echo $rowsFooterHTML;
		
		echo '</tfoot>';	
		echo "</table>";
		
		echo "<script>$('#credentialUserListTable').DataTable({'autoWidth': true,'iDisplayLength': 7,'order': [[ 0, 'desc' ]],'bFilter': false,'bLengthChange': false});</script>";
	
		mysql_close();
		mysql_close();
		mysql_close();
		//End listUserCred Function

	break;
	
	case "destroyAllCredentials":

		//Start updateUserInfo Function
		$username = $_SESSION['session_user'];

		
		//Start Connection
		$mysqli = new mysqli($dbServer,$dbUser,$dbPass,$dbName);
		
		/* check connection */
		if (mysqli_connect_errno()) {
		    printf("Connect failed: %s\n", mysqli_connect_error());
		    exit();
		}
		
		$mysqli->query("DELETE FROM sessions WHERE owner = '$username' AND username != '$username'");
		
		/* close connection */
		$mysqli->close();
	
		return true;
		//End updateUserInfo Function
	
	break;		
}

?>
